<template>
  <div>
    <p style="text-align: left">
      <el-button type="success" @click="dialogVisibleAddRole = true">
        <el-icon> <Plus /> </el-icon>添加</el-button
      >
      <el-button type="danger" @click="batchDel"
        ><el-icon> <Delete /> </el-icon>>批量删除</el-button
      >
    </p>
    <br />
    <el-table
      :data="roleList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column prop="RoleName" label="角色名称" align="center" />
      <el-table-column prop="RoleDesc" label="角色权限描述" align="center" />
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="danger" @click="delRole(scope.row.RoleId)"
            >删除</el-button
          >
          <!-- <el-button type="info">编辑</el-button> -->
          <el-button
            type="success"
            @click="handlePermission(scope.$index, scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisibleAddRole"
      title="提示"
      width="45%"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addRole(ruleFormRef)">
            添加
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" align="center">
      <span>角色名称：{{ roleName }}</span>
      <el-tree
        style="max-width: 600px"
        :data="permissionList"
        default-expand-all
        show-checkbox
        node-key="Permission_Id"
        :props="defaultProps"
        ref="treeRef"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlerSaveData"> 添加 </el-button>
        </div>
      </template>
    </el-dialog>
    <br />
    <table style="margin: auto">
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </td>
      </tr>
    </table>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive } from "vue";
import { FormInstance, FormRules, ElTable } from "element-plus";
import { ElTree } from "element-plus";

interface tableData {
  name: string;
  address: string;
}
const page = ref(1);
const roleId = ref(0);
const size = ref(10);
const roleName = ref("");
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const totalCount = ref(0);
const roleList = ref([]);
const permissionList = ref([]);
const multipleSelection = ref<tableData[]>([]);
const dialogVisibleAddRole = ref(false);
const ruleFormRef = ref<FormInstance>();
const treeRef = ref<InstanceType<typeof ElTree>>();
const formSize = ref("default");

const formInline = reactive({
  roleName: "",
});

interface RuleForm {
  roleName: string;
  roleDesc: string;
}

const form = reactive<RuleForm>({
  roleName: "",
  roleDesc: "",
});

const rules = reactive<FormRules<RuleForm>>({
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 30, message: "长度在2到30之间", trigger: "blur" },
  ],
  roleDesc: [
    {
      required: true,
      message: "请输入角色描述",
      trigger: "change",
    },
  ],
});

const handleClose = (done: () => void) => {
  done();
};

const getPermissionList = () => {
  axios.get("RBAC/GetMemusAll").then((res) => {
    permissionList.value = res.data.Data;
  });
};

const handlerSaveData = () => {
  let keys = treeRef.value!.getCheckedKeys();
  let halfKeys = treeRef.value!.getHalfCheckedKeys();
  let permIds = keys.concat(halfKeys);
  let obj = {
    roleId: roleId.value.toString(),
    permssions: permIds.toString(),
  };

  axios.post("Role/AddRolePermission", obj).then((res) => {
    if (res.data.Code == 200) {
      ElMessage.success(res.data.Message);
      dialogVisible.value = false;
    } else {
      ElMessage.error(res.data.Message);
    }
  });
};

const handlePermission = (index, row) => {
  roleName.value = row.RoleName;
  roleId.value = row.RoleId;
  axios
    .get(`Role/GetRoleIdByPermissionIds?roleId=${row.RoleId}`)
    .then((res) => {
      treeRef.value!.setCheckedKeys([]);
      res.data.Data.forEach((element) => {
        treeRef.value!.setChecked(element, true, true);
      });
    });
  dialogVisible.value = true;
};

const addRole = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("Role/AddRole", form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message);
          dialogVisibleAddRole.value = false;
          tableData();
        } else {
          ElMessage.error("添加失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleSizeChange = (val: number) => {
  size.value = val;
  tableData();
};

const handleCurrentChange = (val: number) => {
  page.value = val;
  tableData();
};

const tableData = () => {
  axios
    .get("Role/GetPage", {
      params: {
        roleName: formInline.roleName,
        page: page.value,
        size: size.value,
      },
    })
    .then((res) => {
      roleList.value = res.data.Data;
      totalCount.value = res.data.TotalCount;
    });
};
const dialogVisible = ref(false);
const defaultProps = {
  children: "children",
  label: "Permission_Name",
};
const handleSelectionChange = (val: tableData[]) => {
  multipleSelection.value = val;
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const delRole = (RoleId: string) => {
  ElMessageBox.confirm("确认要删除吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 在确认删除时执行的操作，例如调用后端接口删除文件
    axios
      .delete(`Role/DeleteRole?roleId=${RoleId}`)
      .then((res) => {
        if (res.data.Code == 200) {
          ElMessage({
            type: "success",
            message: res.data.Message,
          });
          // 删除成功后刷新数据等操作
          tableData();
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

const batchDel = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请至少选择要删除的角色！");
    return;
  }
  ElMessageBox.confirm("确认要删除吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 在确认删除时执行的操作，例如调用后端接口删除文件
    axios
      .put(`Role/BatchDeleteRoles`, multipleSelection.value)
      .then((res) => {
        if (res.data.Code == 200) {
          ElMessage({
            type: "success",
            message: res.data.Message,
          });
          // 删除成功后刷新数据等操作
          tableData();
        } else {
          ElMessage.error("删除失败");
        }
      })
      .catch(() => {
        ElMessage.error("删除失败");
      });
  });
};

getPermissionList();
tableData();
</script>
<style>
.page-container {
  font-family: "Arial", sans-serif;
  color: #333;
  background-color: #f0f2f5;
  padding: 20px;
}

.header {
  background-color: #409eff;
  padding: 20px;
  text-align: center;
  border-radius: 5px;
  margin-bottom: 20px;
}

.header h1 {
  color: #fff;
  font-size: 24px;
}

.content {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-dialog {
  max-width: 800px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

table {
  margin: 0 auto;
}
</style>
